using Microsoft.AspNetCore.Mvc;
using SqlsugarService.Application.AI.KouZi_AI;
using SqlsugarService.Application.AI.KouZi_AI.Dtos;
using SqlsugarService.Application.AI.LangChain;
using SqlsugarService.Application.AI.LangChain.Dtos;
using SqlsugarService.Application.AI.MES;
using System.ComponentModel.DataAnnotations;
using System.Text.Json;

namespace SqlsugarService.API.Controllers
{
    /// <summary>
    /// MES系统智能助手控制器
    /// 
    /// 提供专门针对MES系统的智能客服功能，包括：
    /// - 业务咨询和操作指导
    /// - 数据查询和分析
    /// - 工作流程协助
    /// - 异常处理建议
    /// - 报表生成协助
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    public class MESAssistantController : ControllerBase
    {
        private readonly IKouZiAIService _kouziAIService;
        private readonly ILangChainService _langChainService;
        private readonly IMESLangChainService _mesLangChainService;
        private readonly IMESToolService _mesToolService;
        private readonly IMESKnowledgeService _mesKnowledgeService;
        private readonly ILogger<MESAssistantController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="kouziAIService">扣子AI服务</param>
        /// <param name="langChainService">LangChain服务</param>
        /// <param name="mesToolService">MES工具服务</param>
        /// <param name="mesKnowledgeService">MES知识库服务</param>
        /// <param name="logger">日志记录器</param>
        public MESAssistantController(
            IKouZiAIService kouziAIService,
            ILangChainService langChainService,
            IMESLangChainService mesLangChainService,
            IMESToolService mesToolService,
            IMESKnowledgeService mesKnowledgeService,
            ILogger<MESAssistantController> logger)
        {
            _kouziAIService = kouziAIService ?? throw new ArgumentNullException(nameof(kouziAIService));
            _langChainService = langChainService ?? throw new ArgumentNullException(nameof(langChainService));
            _mesLangChainService = mesLangChainService ?? throw new ArgumentNullException(nameof(mesLangChainService));
            _mesToolService = mesToolService ?? throw new ArgumentNullException(nameof(mesToolService));
            _mesKnowledgeService = mesKnowledgeService ?? throw new ArgumentNullException(nameof(mesKnowledgeService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// MES智能助手对话接口
        /// </summary>
        /// <param name="request">对话请求</param>
        /// <returns>智能助手回复</returns>
        /// <response code="200">请求成功，返回AI回复</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("chat")]
        [ProducesResponseType(typeof(MESAssistantResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<MESAssistantResponseDto>> ChatAsync([FromBody] MESAssistantRequestDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                _logger.LogInformation($"收到MES助手对话请求，用户ID: {request.UserId}, 内容长度: {request.Message?.Length ?? 0}");

                // 构建专门的MES系统提示词
                var mesSystemPrompt = BuildMESSystemPrompt();

                // 使用LangChain处理带工具调用的对话
                var response = await ProcessMESChatWithToolsAsync(request);

                _logger.LogInformation($"MES助手对话处理完成，成功: {response.Success}");
                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理MES助手对话时发生错误");
                return StatusCode(StatusCodes.Status500InternalServerError,
                    new MESAssistantResponseDto
                    {
                        Success = false,
                        ErrorMessage = "服务暂时不可用，请稍后重试"
                    });
            }
        }

        /// <summary>
        /// MES智能助手对话接口 - 使用扣子AI（备用方案）
        /// </summary>
        /// <param name="request">对话请求</param>
        /// <returns>智能助手回复</returns>
        /// <response code="200">请求成功，返回AI回复</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("chat-kouzi")]
        [ProducesResponseType(typeof(MESAssistantResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<MESAssistantResponseDto>> ChatWithKouziAsync([FromBody] MESAssistantRequestDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                _logger.LogInformation($"收到MES助手扣子AI对话请求，用户ID: {request.UserId}, 内容长度: {request.Message?.Length ?? 0}");

                // 使用扣子AI作为备用方案
                var kouziRequest = new KouZiAIRequestDto
                {
                    Content = request.Message ?? string.Empty,
                    UserId = request.UserId,
                    ConversationId = request.ConversationId,
                    Stream = false,
                    AutoSaveHistory = true
                };

                var kouziResponse = await _kouziAIService.SendMessageAsync(kouziRequest);

                var response = new MESAssistantResponseDto
                {
                    Success = kouziResponse.Success,
                    Message = kouziResponse.Content,
                    ConversationId = kouziResponse.ConversationId,
                    Source = "KouZiAI",
                    CreatedAt = kouziResponse.CreatedAt,
                    ErrorMessage = kouziResponse.ErrorMessage
                };

                // 分析回复内容，判断是否需要工具调用
                if (kouziResponse.Success && !string.IsNullOrEmpty(kouziResponse.Content))
                {
                    var toolActions = AnalyzeForToolActions(kouziResponse.Content);
                    response.RequiredActions = toolActions;
                    response.NeedsToolExecution = toolActions?.Any() == true;
                }

                _logger.LogInformation($"MES助手扣子AI对话处理完成，成功: {response.Success}");
                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理MES助手扣子AI对话时发生错误");
                return StatusCode(StatusCodes.Status500InternalServerError,
                    new MESAssistantResponseDto
                    {
                        Success = false,
                        ErrorMessage = "服务暂时不可用，请稍后重试",
                        Source = "KouZiAI",
                        CreatedAt = DateTime.UtcNow
                    });
            }
        }

        /// <summary>
        /// MES智能助手流式对话接口
        /// </summary>
        /// <param name="request">对话请求</param>
        /// <returns>流式AI回复</returns>
        /// <response code="200">请求成功，返回流式AI回复</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("chat-stream")]
        [ProducesResponseType(typeof(List<KouZiAIStreamResponseDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<List<KouZiAIStreamResponseDto>>> ChatStreamAsync([FromBody] MESAssistantRequestDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                _logger.LogInformation($"收到MES助手流式对话请求，用户ID: {request.UserId}");

                var kouziRequest = new KouZiAIRequestDto
                {
                    Content = request.Message,
                    UserId = request.UserId,
                    ConversationId = request.ConversationId,
                    Stream = true,
                    AutoSaveHistory = true
                };

                var streamResponse = await _kouziAIService.SendStreamMessageAsync(kouziRequest);

                _logger.LogInformation($"MES助手流式对话完成，事件数: {streamResponse?.Count ?? 0}");
                return Ok(streamResponse);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理MES助手流式对话时发生错误");
                return StatusCode(StatusCodes.Status500InternalServerError,
                    new List<KouZiAIStreamResponseDto>
                    {
                        new KouZiAIStreamResponseDto
                        {
                            Event = "error",
                            Content = "服务暂时不可用，请稍后重试",
                            IsCompleted = true,
                            Timestamp = DateTime.UtcNow
                        }
                    });
            }
        }

        /// <summary>
        /// 执行MES业务工具操作
        /// </summary>
        /// <param name="request">工具执行请求</param>
        /// <returns>工具执行结果</returns>
        /// <response code="200">工具执行成功</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("execute-tool")]
        [ProducesResponseType(typeof(MESToolExecutionResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<MESToolExecutionResponseDto>> ExecuteToolAsync([FromBody] MESToolExecutionRequestDto request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                _logger.LogInformation($"收到MES工具执行请求，工具: {request.ToolName}, 用户: {request.UserId}");

                var result = await ExecuteMESToolAsync(request);

                _logger.LogInformation($"MES工具执行完成，成功: {result.Success}");
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行MES工具时发生错误");
                return StatusCode(StatusCodes.Status500InternalServerError,
                    new MESToolExecutionResponseDto
                    {
                        Success = false,
                        ErrorMessage = "工具执行失败，请稍后重试"
                    });
            }
        }

        /// <summary>
        /// 获取MES系统帮助信息
        /// </summary>
        /// <returns>帮助信息</returns>
        /// <response code="200">成功返回帮助信息</response>
        [HttpGet("help")]
        [ProducesResponseType(typeof(MESHelpResponseDto), StatusCodes.Status200OK)]
        public ActionResult<MESHelpResponseDto> GetHelp()
        {
            var help = new MESHelpResponseDto
            {
                Introduction = "欢迎使用MES系统智能助手！我可以帮助您：",
                Capabilities = new List<string>
                {
                    "🔍 查询生产订单、物料库存、设备状态",
                    "📋 协助创建和更新生产计划",
                    "🔧 提供工艺流程指导和操作建议",
                    "📊 生成生产报表和质量分析",
                    "⚠️ 协助处理异常和故障诊断",
                    "📖 解答MES系统使用问题"
                },
                Examples = new List<MESExampleDto>
                {
                    new MESExampleDto { Question = "查询今天的生产订单", Description = "获取当日所有生产订单信息" },
                    new MESExampleDto { Question = "物料A001的库存情况", Description = "查询指定物料的库存状态" },
                    new MESExampleDto { Question = "如何创建新的生产计划", Description = "获取生产计划创建的操作指导" },
                    new MESExampleDto { Question = "设备故障处理流程", Description = "了解设备异常的处理步骤" }
                },
                Tips = new List<string>
                {
                    "描述问题时请尽量具体，包含相关的订单号、物料编码等信息",
                    "我可以帮您执行一些基本的数据查询和操作",
                    "对于复杂的业务流程，我会提供详细的步骤指导",
                    "如需人工协助，我会为您推荐合适的联系方式"
                }
            };

            return Ok(help);
        }

        /// <summary>
        /// 清除对话历史
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="conversationId">会话ID（可选）</param>
        /// <returns>操作结果</returns>
        /// <response code="200">清除成功</response>
        /// <response code="400">参数无效</response>
        [HttpDelete("clear-history")]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<ActionResult<bool>> ClearHistoryAsync(
            [FromQuery, Required] string userId,
            [FromQuery] string? conversationId = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userId))
                {
                    return BadRequest(new { error = "用户ID不能为空" });
                }

                _logger.LogInformation($"清除MES助手对话历史，用户: {userId}, 会话: {conversationId ?? "全部"}");

                // 同时清除LangChain和KouZi的对话历史
                var langChainResult = await _langChainService.ClearMemoryAsync(userId, conversationId);

                _logger.LogInformation($"对话历史清除完成，结果: {langChainResult}");
                return Ok(langChainResult);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清除MES助手对话历史时发生错误");
                return Ok(false);
            }
        }

        /// <summary>
        /// 搜索MES知识库
        /// </summary>
        /// <param name="query">搜索关键词</param>
        /// <param name="category">知识分类</param>
        /// <returns>相关知识条目</returns>
        /// <response code="200">搜索成功</response>
        [HttpGet("knowledge/search")]
        [ProducesResponseType(typeof(List<MESKnowledgeItemDto>), StatusCodes.Status200OK)]
        public async Task<ActionResult<List<MESKnowledgeItemDto>>> SearchKnowledgeAsync(
            [FromQuery] string query,
            [FromQuery] string? category = null)
        {
            try
            {
                _logger.LogInformation($"搜索MES知识库，关键词: {query}, 分类: {category}");

                var results = await _mesKnowledgeService.SearchKnowledgeAsync(query, category);

                return Ok(results);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索知识库时发生错误");
                return Ok(new List<MESKnowledgeItemDto>());
            }
        }

        /// <summary>
        /// 获取MES常见问题
        /// </summary>
        /// <param name="category">问题分类</param>
        /// <returns>常见问题列表</returns>
        /// <response code="200">获取成功</response>
        [HttpGet("knowledge/faqs")]
        [ProducesResponseType(typeof(List<MESFAQDto>), StatusCodes.Status200OK)]
        public async Task<ActionResult<List<MESFAQDto>>> GetFAQsAsync([FromQuery] string? category = null)
        {
            try
            {
                _logger.LogInformation($"获取MES常见问题，分类: {category}");

                var results = await _mesKnowledgeService.GetFAQsAsync(category);

                return Ok(results);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取常见问题时发生错误");
                return Ok(new List<MESFAQDto>());
            }
        }

        /// <summary>
        /// 获取操作指南
        /// </summary>
        /// <param name="operation">操作类型</param>
        /// <returns>操作指南</returns>
        /// <response code="200">获取成功</response>
        /// <response code="404">未找到指南</response>
        [HttpGet("knowledge/guide/{operation}")]
        [ProducesResponseType(typeof(MESOperationGuideDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<MESOperationGuideDto>> GetOperationGuideAsync(string operation)
        {
            try
            {
                _logger.LogInformation($"获取操作指南: {operation}");

                var guide = await _mesKnowledgeService.GetOperationGuideAsync(operation);

                if (guide == null)
                {
                    return NotFound(new { message = $"未找到操作指南: {operation}" });
                }

                return Ok(guide);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取操作指南时发生错误");
                return NotFound(new { message = "获取操作指南失败" });
            }
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        /// <returns>服务状态</returns>
        /// <response code="200">服务正常</response>
        /// <response code="503">服务不可用</response>
        [HttpGet("health")]
        [ProducesResponseType(typeof(MESHealthCheckResponseDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
        public async Task<ActionResult<MESHealthCheckResponseDto>> HealthCheckAsync()
        {
            try
            {
                var kouziHealth = await _kouziAIService.HealthCheckAsync();
                var langChainHealth = await _langChainService.HealthCheckAsync();

                var response = new MESHealthCheckResponseDto
                {
                    IsHealthy = kouziHealth || langChainHealth, // 至少一个服务可用
                    KouZiAIStatus = kouziHealth ? "OK" : "Unavailable",
                    LangChainStatus = langChainHealth ? "OK" : "Unavailable",
                    Timestamp = DateTime.UtcNow
                };

                if (response.IsHealthy)
                {
                    return Ok(response);
                }
                else
                {
                    return StatusCode(StatusCodes.Status503ServiceUnavailable, response);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "MES助手健康检查失败");
                return StatusCode(StatusCodes.Status503ServiceUnavailable,
                    new MESHealthCheckResponseDto
                    {
                        IsHealthy = false,
                        KouZiAIStatus = "Error",
                        LangChainStatus = "Error",
                        Timestamp = DateTime.UtcNow
                    });
            }
        }

        #region 私有方法

        /// <summary>
        /// 使用MES专用LangChain服务处理对话并自动调用工具
        /// </summary>
        /// <param name="request">对话请求</param>
        /// <returns>处理结果</returns>
        private async Task<MESAssistantResponseDto> ProcessMESChatWithToolsAsync(MESAssistantRequestDto request)
        {
            try
            {
                _logger.LogInformation("开始使用MES专用LangChain处理对话，用户: {UserId}", request.UserId);

                // 使用MES专用LangChain服务，自动处理工具调用
                var result = await _mesLangChainService.ProcessMESChatAsync(
                    request.Message,
                    request.UserId,
                    request.ConversationId);

                return new MESAssistantResponseDto
                {
                    Success = result.Success,
                    Message = result.Message,
                    ConversationId = result.SessionId,
                    Source = "MESLangChain",
                    CreatedAt = DateTime.UtcNow,
                    ErrorMessage = result.ErrorMessage,
                    NeedsToolExecution = false // MES LangChain已自动处理工具调用
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "MES LangChain处理对话失败");
                return new MESAssistantResponseDto
                {
                    Success = false,
                    ErrorMessage = "智能助手暂时不可用，请稍后重试",
                    Source = "MESLangChain",
                    CreatedAt = DateTime.UtcNow
                };
            }
        }

        /// <summary>
        /// 构建增强的消息内容
        /// </summary>
        /// <param name="request">原始请求</param>
        /// <returns>增强后的消息</returns>
        private string BuildEnhancedMessage(MESAssistantRequestDto request)
        {
            var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            return $@"[时间: {timestamp}]
[用户ID: {request.UserId}]
[会话ID: {request.ConversationId ?? "新会话"}]

用户消息: {request.Message}

请根据用户的需求，智能选择合适的工具来帮助用户。如果需要查询数据，请调用相应的查询工具。";
        }

        /// <summary>
        /// 获取MES工具定义列表
        /// </summary>
        /// <returns>工具定义列表</returns>
        private List<ToolDefinition> GetMESToolDefinitions()
        {
            return new List<ToolDefinition>
            {
                new ToolDefinition
                {
                    Function = new ToolFunction
                    {
                        Name = "query_production_orders",
                        Description = "查询生产订单信息，支持按订单号、日期范围、状态等条件筛选",
                        Parameters = new ToolParameters
                        {
                            Type = "object",
                            Properties = new Dictionary<string, ToolProperty>
                            {
                                ["orderNumber"] = new ToolProperty { Type = "string", Description = "生产订单号" },
                                ["startDate"] = new ToolProperty { Type = "string", Description = "开始日期，格式：yyyy-MM-dd" },
                                ["endDate"] = new ToolProperty { Type = "string", Description = "结束日期，格式：yyyy-MM-dd" },
                                ["status"] = new ToolProperty { Type = "string", Description = "订单状态：待开始、进行中、已完成、已取消" },
                                ["productCode"] = new ToolProperty { Type = "string", Description = "产品编码" }
                            }
                        }
                    }
                },
                new ToolDefinition
                {
                    Function = new ToolFunction
                    {
                        Name = "query_material_inventory",
                        Description = "查询物料库存信息，支持按物料编码、名称、分类等条件筛选",
                        Parameters = new ToolParameters
                        {
                            Type = "object",
                            Properties = new Dictionary<string, ToolProperty>
                            {
                                ["materialCode"] = new ToolProperty { Type = "string", Description = "物料编码" },
                                ["materialName"] = new ToolProperty { Type = "string", Description = "物料名称" },
                                ["category"] = new ToolProperty { Type = "string", Description = "物料分类" },
                                ["lowStock"] = new ToolProperty { Type = "boolean", Description = "是否只查询低库存物料" }
                            }
                        }
                    }
                },
                new ToolDefinition
                {
                    Function = new ToolFunction
                    {
                        Name = "query_sales_orders",
                        Description = "查询销售订单信息，支持按订单号、客户、日期等条件筛选",
                        Parameters = new ToolParameters
                        {
                            Type = "object",
                            Properties = new Dictionary<string, ToolProperty>
                            {
                                ["orderNumber"] = new ToolProperty { Type = "string", Description = "销售订单号" },
                                ["customerName"] = new ToolProperty { Type = "string", Description = "客户名称" },
                                ["startDate"] = new ToolProperty { Type = "string", Description = "开始日期" },
                                ["endDate"] = new ToolProperty { Type = "string", Description = "结束日期" },
                                ["status"] = new ToolProperty { Type = "string", Description = "订单状态" }
                            }
                        }
                    }
                },
                new ToolDefinition
                {
                    Function = new ToolFunction
                    {
                        Name = "query_bom_info",
                        Description = "查询BOM（物料清单）信息，支持按产品ID、产品编码查询",
                        Parameters = new ToolParameters
                        {
                            Type = "object",
                            Properties = new Dictionary<string, ToolProperty>
                            {
                                ["productId"] = new ToolProperty { Type = "integer", Description = "产品ID" },
                                ["productCode"] = new ToolProperty { Type = "string", Description = "产品编码" },
                                ["includeSubComponents"] = new ToolProperty { Type = "boolean", Description = "是否包含子组件" }
                            }
                        }
                    }
                },
                new ToolDefinition
                {
                    Function = new ToolFunction
                    {
                        Name = "generate_production_report",
                        Description = "生成生产统计报表，支持按时间范围、产品、车间等维度统计",
                        Parameters = new ToolParameters
                        {
                            Type = "object",
                            Properties = new Dictionary<string, ToolProperty>
                            {
                                ["reportType"] = new ToolProperty { Type = "string", Description = "报表类型：daily、weekly、monthly" },
                                ["startDate"] = new ToolProperty { Type = "string", Description = "开始日期" },
                                ["endDate"] = new ToolProperty { Type = "string", Description = "结束日期" },
                                ["productCode"] = new ToolProperty { Type = "string", Description = "产品编码" },
                                ["workshop"] = new ToolProperty { Type = "string", Description = "车间名称" }
                            }
                        }
                    }
                }
            };
        }

        /// <summary>
        /// 执行工具调用
        /// </summary>
        /// <param name="toolCalls">工具调用列表</param>
        /// <returns>工具执行结果</returns>
        private async Task<List<object>> ExecuteToolCallsAsync(List<ToolCall> toolCalls)
        {
            var results = new List<object>();

            foreach (var toolCall in toolCalls)
            {
                try
                {
                    var parameters = JsonSerializer.Deserialize<Dictionary<string, object>>(toolCall.Function.Arguments);

                    var result = toolCall.Function.Name switch
                    {
                        "query_production_orders" => await _mesToolService.QueryProductionOrdersAsync(parameters),
                        "query_material_inventory" => await _mesToolService.QueryMaterialInventoryAsync(parameters),
                        "query_sales_orders" => await _mesToolService.QuerySalesOrdersAsync(parameters),
                        "query_bom_info" => await _mesToolService.QueryBOMInfoAsync(parameters),
                        "generate_production_report" => await _mesToolService.GenerateProductionReportAsync(parameters),
                        _ => new { error = $"未知的工具: {toolCall.Function.Name}" }
                    };

                    results.Add(new
                    {
                        toolName = toolCall.Function.Name,
                        success = true,
                        data = result
                    });
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "执行工具 {ToolName} 失败", toolCall.Function.Name);
                    results.Add(new
                    {
                        toolName = toolCall.Function.Name,
                        success = false,
                        error = ex.Message
                    });
                }
            }

            return results;
        }

        /// <summary>
        /// 构建MES系统专用的系统提示词
        /// </summary>
        /// <returns>系统提示词</returns>
        private string BuildMESSystemPrompt()
        {
            return @"你是一个专业的MES（制造执行系统）智能助手，专门为制造企业提供生产管理支持。

你的能力范围包括：
1. 生产管理：生产订单查询、生产计划制定、进度跟踪
2. 物料管理：库存查询、物料需求计算、采购建议
3. 质量管理：质检数据分析、不良品处理、质量追溯
4. 设备管理：设备状态监控、维护计划、故障诊断
5. 工艺管理：工艺流程指导、参数优化建议
6. 报表分析：生产效率分析、成本统计、趋势预测

你拥有以下工具来帮助用户：
- query_production_orders: 查询生产订单信息
- query_material_inventory: 查询物料库存信息
- query_sales_orders: 查询销售订单信息
- query_bom_info: 查询BOM物料清单信息
- generate_production_report: 生成生产统计报表

回答时请：
- 使用专业但易懂的语言
- 当用户需要查询数据时，主动调用相应的工具
- 根据工具返回的数据，提供清晰的分析和建议
- 提供具体的操作步骤和实用建议
- 必要时询问更多细节以提供准确帮助

如果遇到超出能力范围的问题，请诚实说明并建议联系相关专业人员。";
        }

        /// <summary>
        /// 分析回复内容中的工具调用需求
        /// </summary>
        /// <param name="content">AI回复内容</param>
        /// <returns>需要的工具操作列表</returns>
        private List<MESToolActionDto>? AnalyzeForToolActions(string content)
        {
            if (string.IsNullOrEmpty(content))
                return null;

            var actions = new List<MESToolActionDto>();

            // 分析是否需要数据查询
            if (content.Contains("查询") || content.Contains("获取") || content.Contains("搜索"))
            {
                if (content.Contains("订单"))
                    actions.Add(new MESToolActionDto { ActionType = "query_orders", Description = "查询生产订单" });

                if (content.Contains("库存") || content.Contains("物料"))
                    actions.Add(new MESToolActionDto { ActionType = "query_inventory", Description = "查询库存信息" });

                if (content.Contains("设备"))
                    actions.Add(new MESToolActionDto { ActionType = "query_equipment", Description = "查询设备状态" });
            }

            // 分析是否需要生成报表
            if (content.Contains("报表") || content.Contains("统计") || content.Contains("分析"))
            {
                actions.Add(new MESToolActionDto { ActionType = "generate_report", Description = "生成报表" });
            }

            return actions.Any() ? actions : null;
        }

        /// <summary>
        /// 执行MES业务工具
        /// </summary>
        /// <param name="request">工具执行请求</param>
        /// <returns>执行结果</returns>
        private async Task<MESToolExecutionResponseDto> ExecuteMESToolAsync(MESToolExecutionRequestDto request)
        {
            var response = new MESToolExecutionResponseDto
            {
                ToolName = request.ToolName,
                ExecutedAt = DateTime.UtcNow
            };

            try
            {
                switch (request.ToolName.ToLower())
                {
                    case "query_orders":
                    case "query_production_orders":
                        response.Result = await _mesToolService.QueryProductionOrdersAsync(request.Parameters);
                        response.Success = true;
                        break;

                    case "query_inventory":
                    case "query_material_inventory":
                        response.Result = await _mesToolService.QueryMaterialInventoryAsync(request.Parameters);
                        response.Success = true;
                        break;

                    case "query_sales_orders":
                        response.Result = await _mesToolService.QuerySalesOrdersAsync(request.Parameters);
                        response.Success = true;
                        break;

                    case "query_bom":
                    case "query_bom_info":
                        response.Result = await _mesToolService.QueryBOMInfoAsync(request.Parameters);
                        response.Success = true;
                        break;

                    case "generate_report":
                    case "generate_production_report":
                        response.Result = await _mesToolService.GenerateProductionReportAsync(request.Parameters);
                        response.Success = true;
                        break;

                    case "create_production_plan":
                        response.Result = await _mesToolService.CreateProductionPlanAsync(request.Parameters);
                        response.Success = true;
                        break;

                    case "update_order_status":
                        response.Result = await _mesToolService.UpdateOrderStatusAsync(request.Parameters);
                        response.Success = true;
                        break;

                    default:
                        response.Success = false;
                        response.ErrorMessage = $"不支持的工具: {request.ToolName}";
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行MES工具 {ToolName} 失败", request.ToolName);
                response.Success = false;
                response.ErrorMessage = ex.Message;
            }

            return response;
        }

        #endregion
    }

    #region 数据传输对象

    /// <summary>
    /// MES助手请求DTO
    /// </summary>
    public class MESAssistantRequestDto
    {
        /// <summary>
        /// 用户消息
        /// </summary>
        [Required(ErrorMessage = "消息内容不能为空")]
        public string Message { get; set; } = string.Empty;

        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserId { get; set; } = "default_user";

        /// <summary>
        /// 会话ID
        /// </summary>
        public string? ConversationId { get; set; }
    }

    /// <summary>
    /// MES助手响应DTO
    /// </summary>
    public class MESAssistantResponseDto
    {
        /// <summary>
        /// 操作是否成功
        /// </summary>
        public bool Success { get; set; } = true;

        /// <summary>
        /// 回复消息
        /// </summary>
        public string? Message { get; set; }

        /// <summary>
        /// 会话ID
        /// </summary>
        public string? ConversationId { get; set; }

        /// <summary>
        /// 回复来源
        /// </summary>
        public string? Source { get; set; }

        /// <summary>
        /// 是否需要工具执行
        /// </summary>
        public bool NeedsToolExecution { get; set; }

        /// <summary>
        /// 需要的操作
        /// </summary>
        public List<MESToolActionDto>? RequiredActions { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedAt { get; set; } = DateTime.UtcNow;

        /// <summary>
        /// 错误信息
        /// </summary>
        public string? ErrorMessage { get; set; }
    }

    /// <summary>
    /// MES工具操作DTO
    /// </summary>
    public class MESToolActionDto
    {
        /// <summary>
        /// 操作类型
        /// </summary>
        public string ActionType { get; set; } = string.Empty;

        /// <summary>
        /// 操作描述
        /// </summary>
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 操作参数
        /// </summary>
        public Dictionary<string, object>? Parameters { get; set; }
    }

    /// <summary>
    /// MES工具执行请求DTO
    /// </summary>
    public class MESToolExecutionRequestDto
    {
        /// <summary>
        /// 工具名称
        /// </summary>
        [Required(ErrorMessage = "工具名称不能为空")]
        public string ToolName { get; set; } = string.Empty;

        /// <summary>
        /// 执行参数
        /// </summary>
        public Dictionary<string, object>? Parameters { get; set; }

        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserId { get; set; } = "default_user";

        /// <summary>
        /// 会话ID
        /// </summary>
        public string? ConversationId { get; set; }
    }

    /// <summary>
    /// MES工具执行响应DTO
    /// </summary>
    public class MESToolExecutionResponseDto
    {
        /// <summary>
        /// 执行是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 工具名称
        /// </summary>
        public string? ToolName { get; set; }

        /// <summary>
        /// 执行结果
        /// </summary>
        public object? Result { get; set; }

        /// <summary>
        /// 执行时间
        /// </summary>
        public DateTime ExecutedAt { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string? ErrorMessage { get; set; }
    }

    /// <summary>
    /// MES帮助响应DTO
    /// </summary>
    public class MESHelpResponseDto
    {
        /// <summary>
        /// 介绍信息
        /// </summary>
        public string Introduction { get; set; } = string.Empty;

        /// <summary>
        /// 功能列表
        /// </summary>
        public List<string> Capabilities { get; set; } = new List<string>();

        /// <summary>
        /// 使用示例
        /// </summary>
        public List<MESExampleDto> Examples { get; set; } = new List<MESExampleDto>();

        /// <summary>
        /// 使用技巧
        /// </summary>
        public List<string> Tips { get; set; } = new List<string>();
    }

    /// <summary>
    /// MES示例DTO
    /// </summary>
    public class MESExampleDto
    {
        /// <summary>
        /// 示例问题
        /// </summary>
        public string Question { get; set; } = string.Empty;

        /// <summary>
        /// 问题描述
        /// </summary>
        public string Description { get; set; } = string.Empty;
    }

    /// <summary>
    /// MES健康检查响应DTO
    /// </summary>
    public class MESHealthCheckResponseDto
    {
        /// <summary>
        /// 是否健康
        /// </summary>
        public bool IsHealthy { get; set; }

        /// <summary>
        /// 扣子AI状态
        /// </summary>
        public string KouZiAIStatus { get; set; } = string.Empty;

        /// <summary>
        /// LangChain状态
        /// </summary>
        public string LangChainStatus { get; set; } = string.Empty;

        /// <summary>
        /// 检查时间
        /// </summary>
        public DateTime Timestamp { get; set; }
    }

    #endregion
}